package com.example.server.controller;

import com.example.server.entity.Product;
import com.example.server.service.ProductService;
import com.example.server.util.Util;
import org.apache.catalina.LifecycleState;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.event.PaintEvent;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("product")
@CrossOrigin("http://localhost:5173")
public class ProductController extends BaseController{

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @PostMapping("create")
    @ResponseBody
    private boolean create(@RequestPart MultipartFile file,@RequestPart Product product){
        String path = "D:/softwear/shixun/project-team06/photo/product";
        product.setPicture(Util.savePicture(file,path));
        productService.create(product);
        return true;
    }

    @GetMapping("queryAllCommented")
    @ResponseBody
    private List<Product> queryAllCommented(){
        return productService.queryList("queryAllCommented",null);
    }

    @GetMapping("queryAll")
    @ResponseBody
    private List<Product> queryAll(){
        return productService.queryAll();
    }

    @DeleteMapping("removeById")
    @ResponseBody
    private boolean removeById(@RequestBody Map<String, BigInteger> map) {
        BigInteger pid = map.get("pid");
        productService.removeById(pid);
        return true;
    }

    @GetMapping("queryByAccount")
    @ResponseBody
    private List<Product> queryByAccount(@RequestParam String account) {
        return productService.queryList("queryByAccount", account);
    }

    @GetMapping("queryById")
    @ResponseBody
    private Product queryById(@RequestParam BigInteger pid) {
        System.out.println(pid);
        Product product = productService.queryOne("queryById",pid);
        session.setAttribute("product",product);
        return product;
    }

    @PutMapping("modify")
    @ResponseBody
    private boolean modify(@RequestPart(required = false) MultipartFile file, @RequestPart Product product) {
        System.out.println(file);
        if (file != null) {
            product.setPicture(Util.savePicture(file, "D:/softwear/shixun/project-team06/photo/product"));
        }
        productService.modify(product);
        return true;
    }

    @GetMapping("queryByKid")
    @ResponseBody
    private List<Product> queryByKid(@RequestParam BigInteger kid) {
        return productService.queryList("queryByKid", kid);
    }
}